<?php
/*
 * Created on 2011-4-14
 * use for html generate
 * The file name html_generate.php
 * Author yangyong
 */
class HtmlGenerateComponent extends Object {
	
	/**
	 *use for generate html
	 *@param $type is stirng
	 *@param $url is string
	 *@param $suf is intval, such as article id, a suffix for create html name.
	 **/
	function generate($type = null, $url = null, $suf = null){
		if(empty($url)) return array('rlt'=>false, 'msg'=>'Param error');

		if(!class_exists('File')){
			return array('rlt' => false, 'msg' => 'Please install the Filesystem extension support!');
		}
		$basepath   = dirname(dirname(dirname(__FILE__)));
		$htmlfolder = $basepath.DIRECTORY_SEPARATOR.'webroot'.DIRECTORY_SEPARATOR.'htmls';
		if(!file_exists($htmlfolder)){
			$mkresult = mkdir($htmlfolder, 0755);
			if(!$mkresult){
				return array('rlt' => false, 'msg' => 'Create folder "'.$htmlfolder.'" faild.');
			}
		}
		if(!is_writeable($htmlfolder)){
			return array('rlt' => false, 'msg' => 'Please install the Filesystem extension support!');
		}
		
		$htmlcontents = file_get_contents($url);
		if(empty($htmlcontents)){
			return array('rlt' => false, 'msg' => 'Can not get the contents.');
		}
		$htmlname = empty($suf) ? date('His').date('Ymd').'-'.mt_rand(100, 1000) : base_convert($suf, 10, 2).'-'.$suf;
		switch($type){
			case 'index':
				$htmlname = 'index';
				$htmlfolder = $basepath.DIRECTORY_SEPARATOR.'webroot';
				break;
			default:
				break;
		}
		$htmlfile = $htmlfolder.DIRECTORY_SEPARATOR.$htmlname.'.html';
		if(file_exists($htmlfile)){
			if(!unlink($htmlfile)){
				return array('rlt' => false, 'msg' => 'Unlink html file faild.');
			}
		}
		$newhtml  = new file($htmlfile, true);
		if(!file_exists($htmlfile)){ 
			return array('rlt' => false, 'msg' => 'Create html file faild.');
		}
		
		$htmlcreate = file_put_contents($newhtml->path, $htmlcontents, LOCK_EX);
		if(empty($htmlcreate)){
			return array('rlt' => false, 'msg' => 'Put contents to html file faild.');
		}
		return array('rlt' => true, 'msg' => $newhtml->name);
	}
}